//
//  CPTextView.m
//  MyAlert
//
//  Created by 美鑫科技 on 16/4/26.
//  Copyright © 2016年 美鑫科技. All rights reserved.
//

#import "CPTextView.h"

@interface CPTextView ()

@property (nonatomic, strong) UILabel *placeHolderLabel;

@end

@implementation CPTextView

- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        self.placeholder = @"";
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textChange) name:UITextViewTextDidChangeNotification object:nil];
    }
    return self;
}

- (void)setPlaceholder:(NSString *)placeholder{
    if (_placeholder != placeholder) {
        _placeholder = placeholder;
        [self.placeHolderLabel removeFromSuperview];
        self.placeHolderLabel = nil;
    }
}

- (void)layoutSubviews{
    if (self.placeholder.length > 0) {
        if (!_placeHolderLabel) {
            _placeHolderLabel = [[UILabel alloc] initWithFrame:CGRectMake(5, 5, self.bounds.size.width - 10, 0)];
            _placeHolderLabel.numberOfLines = 0;
            _placeHolderLabel.font = self.font;
            _placeHolderLabel.backgroundColor = [UIColor clearColor];
            _placeHolderLabel.textColor = [UIColor lightGrayColor];
            _placeHolderLabel.alpha = 0;
            [self addSubview:_placeHolderLabel];
        }
        _placeHolderLabel.text= self.placeholder;
        [_placeHolderLabel sizeToFit];
        [self sendSubviewToBack:_placeHolderLabel];
    }
    if (self.text.length == 0 && self.placeholder.length > 0) {
        [_placeHolderLabel setAlpha:1.0];
    }
}

- (void)textChange{
    if (self.placeholder.length == 0) return;
    if (self.text.length == 0) [self.placeHolderLabel setAlpha:1.0];
    else [self.placeHolderLabel setAlpha:0];
}

@end
